<template>
<div class="group-container">
  <group-header
      v-if="rules.condition"
      :condition.sync="rules.condition"
      :showDelete="showDelete"
      @add="add"
      @removeBuilder="removeBuilder"></group-header>
  <group-body :rules.sync="rules.rules" @removeRow="removeRow" v-bind="$attrs"></group-body>
</div>
</template>

<script>
import groupHeader from '@/components/query-builder/group-header'
import groupBody from '@/components/query-builder/group-body'
export default {
  name: 'query-builder',
  props: ['value', 'showDelete'],
  components: {
    groupHeader,
    groupBody
  },
  data () {
    return {
      rules: {}
    }
  },
  watch: {
    rules (val) {
      this.$emit('input', val)
    }
  },
  methods: {
    add (type) {
      if (type === 'group') {
        // eslint-disable-next-line vue/no-mutating-props
        this.rules.rules.push({
          condition: 'and',
          rules: [
            {
              field: '',
              type: '',
              operator: '',
              value: ''
            }
          ]
        })
      }
      if (type === 'condition') {
        // eslint-disable-next-line vue/no-mutating-props
        this.rules.rules.push({
          field: '',
          type: '',
          operator: '',
          value: ''
        })
      }
    },
    removeRow (index) {
      // eslint-disable-next-line vue/no-mutating-props
      this.rules.rules.splice(index, 1)
    },
    removeBuilder () {
      this.$emit('removeBuilder')
    }
  },
  created () {
    if (JSON.stringify(this.value) !== '{}') {
      this.rules = this.value
    } else {
      this.rules = {
        condition: 'and',
        rules: []
      }
    }
  }
}
</script>

<style scoped lang="scss">
.group-container {
  background: #ffffff;
  padding: 15px;
  position: relative;
  .group-container {
    padding-left: 0;
    .group-header {
      display: flex;
      align-items: center;
      position: relative;
      &::before {
        content: '';
        display: block;
        position: absolute;
        width: 20px;
        height: 1px;
        border-bottom: 1px dashed #00cc00;
        left: -20px;
        top: 50%;
      }
      &::after {
        content: '';
        display: block;
        position: absolute;
        width: 1px;
        border-left: 1px dashed #00cc00;
        height: calc(100% + 30px);
        left: -20px;
        top: calc(-50% - 30px);
      }
    }
  }
}
.group-container .group-container::before {
  content: '';
  display: block;
  position: absolute;
  width: 1px;
  border-left: 1px dashed #00cc00;
  height: calc(100% - 60px);
  left: -20px;
  top: 36px;
}
.rule-list .group-container{}
</style>
